﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using University.Workshop.Business;
using University.Workshop.Model;
using University.Workshop.DataAccess;

namespace University.Workshop.WebApp
{
    public partial class CancelAuction : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            if (PasswordAttemptsManager.Attempts == 0)
            {
                PasswordAttemptsManager.CancelAuction = true;
            }
            if(!PasswordAttemptsManager.CancelAuction)
                PasswordAttemptsManager.Reset();
        }

        protected void BtnConfirm_Click(object sender, EventArgs e)
        {
            PasswordAttemptsManager.Attempts++;
            try
            {
                User user = UserDataAccess.GetUserByEmail(User.Identity.Name);
                if (user.Password.Equals(TbPassword.Text.GetHashCode().ToString()))
                {
                    long prodId = long.Parse(Request["id"]);
                    CancelAuctionManager.CancelAuction(prodId);
                    PasswordAttemptsManager.CancelAuction = false;
                    Response.Write("<script>alert('Auction canceled successfully'); window.location.href = 'UserProducts.aspx';</script>");
                }
                else
                {
                    if (PasswordAttemptsManager.Attempts < 5)
                        Response.Write("<script>alert('Cannot confirm the action, the password is wrong');</script>");
                    else
                    {
                        Response.Write("<script>alert('You have inserted a wrong password 5 times, you will be logged out');</script>");
                        //todo log out user
                        FormsAuthentication.SignOut();
                    }
                }
            }
            catch (Exception exc)
            {
                Response.Write("<script>alert('" + exc.Message + "'); window.location.href = 'UserProducts.aspx';</script>");
            }
        }

        protected void BtnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserProducts.aspx");
        }
    }
}